//
//  DbManager.m
//  DoIT
//
//  Created by 葛欣 on 14/11/22.
//  Copyright (c) 2014年 gex. All rights reserved.
//

#import "DbManager.h"
#import "DbManager.h"
#import <sqlite3.h>
#import "Singleton.h"
#import "FMDB.h"
#ifndef kDatabaseName
#define kDatabaseName @"todo.db"
#endif

@implementation DbManager
singleton_implementation(DbManager);
#pragma mark 重写初始化方法
-(instancetype)init{
    DbManager *manager;
    if((manager=[super init]))
    {
        [manager openDb:kDatabaseName];
    }
    return manager;
}
-(void)openDb:(NSString *)dbname{
    //取得数据库保存路径，通常保存沙盒Documents目录
    NSString *directory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath=[directory stringByAppendingPathComponent:dbname];
    //创建FMDatabaseQueue对象
    self.database=[FMDatabaseQueue databaseQueueWithPath:filePath];
}
-(void)executeNonQuery:(NSString *)sql  withArgumentsInArray:(NSArray *)args{
    //执行更新sql语句，用于插入、修改、删除
    [self.database inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sql withArgumentsInArray:args];
    }];
}
-(NSArray *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)args{
    NSMutableArray *array=[NSMutableArray array];
    [self.database inDatabase:^(FMDatabase *db) {
        //执行查询sql语句
        FMResultSet *result = [db executeQuery:sql withArgumentsInArray:args];
        while (result.next) {
            NSMutableDictionary *dic=[NSMutableDictionary dictionary];
            for (int i=0; i<result.columnCount; ++i) {
                dic[[result columnNameForIndex:i]]=[result objectForColumnIndex:i];
            }
            [array addObject:dic];
        }
    }];
    return array;
}
@end
